package com.example.testdemo.prize_recycler_view;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.testdemo.R;

import java.util.List;


/**
 * Created by 颜 on 04.26.026.
 * 用于中奖信息的 RecyclerView
 */

public class PrizeRecyclerView extends RecyclerView {
    private Adapter mAdapter;
    private Handler mHandler;
    private Runnable mRunnable;
    private int lastItemPosition;
    private OnScrollToBottomListener onScrollToBottomListener;
    private int offsetY;

    public PrizeRecyclerView(Context context) {
        super(context);
        init(context);
    }

    public PrizeRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        lastItemPosition = 3;
        //禁用滚动事件
        setNestedScrollingEnabled(false);
        //item布局文件
        int itemLayout = R.layout.item_prize;
        mAdapter = new Adapter(itemLayout);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        setLayoutManager(layoutManager);
        setAdapter(mAdapter);
        initHandler();
        noScrolling();
    }

    private void noScrolling() {
        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                performClick();
                return true;
            }
        });
    }

    /**
     * 监听可见的最后一个Item位置
     */
    private void listenerLastVisibleItem() {
        RecyclerView.LayoutManager layoutManager = getLayoutManager();
        //判断是当前layoutManager是否为LinearLayoutManager
        // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof LinearLayoutManager) {
            LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
            //获取最后一个可见view的位置
            lastItemPosition = linearManager.findLastVisibleItemPosition();
            View currentBottomView = layoutManager.findViewByPosition(lastItemPosition);
            offsetY = currentBottomView.getBottom();
            offsetY = getHeight() - offsetY;
        }
    }

    /**
     * 监听滚动到底部
     */
    protected boolean isSlideToBottom() {
        return computeVerticalScrollExtent() + computeVerticalScrollOffset() >= computeVerticalScrollRange();
    }

    /**
     * 设置滚动到底部监听器
     */
    public void setOnScrollToBottomListener(OnScrollToBottomListener onScrollToBottomListener){
        this.onScrollToBottomListener = onScrollToBottomListener;
    }

    /**
     * 初始化Handler Runnable
     */
    private void initHandler() {
        mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                smoothScrollBy(0, 10);
                listenerLastVisibleItem();
                if (isSlideToBottom()) {
                    scrollToBottomCallback();
                } else {
                    mHandler.postDelayed(mRunnable, 50);
                }
            }
        };
    }

    /**
     * 当View 脱离窗口的时候，停止线程
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mHandler != null){
            mHandler.removeCallbacks(mRunnable);
            mHandler = null;
            mRunnable = null;
        }
    }

    /**
     * 触发监听器
     */
    private void scrollToBottomCallback() {
        if (onScrollToBottomListener != null){
            onScrollToBottomListener.scrollToBottomCallback();
        }
    }


    /**
     * 开始滚动
     */
    public void startHandler() {
        mHandler.postDelayed(mRunnable, 50);
    }

    /**
     * 添加数据
     */
    public void addData(PrizeMessageBean bean) {
        mAdapter.addData(bean);
    }

    /**
     * 添加数据集合
     */
    public void addData(List<PrizeMessageBean> list) {
        mAdapter.addData(list);
    }

    /**
     * 在下一个可见的位置插入数据
     */
    public void plugInLastData(PrizeMessageBean bean) {
        int position = offsetY > -10 ? lastItemPosition : lastItemPosition + 1;
        mAdapter.addData(position, bean);
    }

    /**
     * 适配器
     *
     * @Param PrizeMessageBean 中奖信息实体类
     */
    private class Adapter extends BaseQuickAdapter<PrizeMessageBean, BaseViewHolder> {

        private Adapter(int layoutId) {
            super(layoutId);
        }

        @Override
        protected void convert(BaseViewHolder helper, PrizeMessageBean item) {
            helper.setText(R.id.prize_text, item.getPrizeMessage());
        }
    }

    /**
     * 滚动到底部监听
     */
    public interface OnScrollToBottomListener {
        void scrollToBottomCallback();
    }


}
